clear
set seed [withheld]

local samplelist $samplelist
foreach sample in `samplelist'{
    if "${routine}"=="_tradables"{
	quietly use ${data}/tradables_lbd_cbsa.dta, clear
	}
    else{
      	quietly use ${data}/cmf_lbd_cbsa_tfp_12.dta, clear
	}

	keep if T==2012
	
	cap sort tvs emp_lbd va ltfp 
	gen linenumber=_n
	
	cap drop tmp*
	gen tmp1 = real(substr(string(cbsa),-3,3))
	gen non_msa = tmp1==999
	drop if non_msa==1 
	drop non_msa tmp1 
	drop if cbsa	==.
	qui egen S	= group(cbsa)

	drop if naics_cmf==""
	if("`sample'"=="digit6${routine}"){
		gen nJ6 = real(substr(naics_cmf,1,6))
		egen J 	= group(nJ6)
	}
	else{
		gen nJ4 = real(substr(naics_cmf,1,4))
		egen J	= group(nJ4)
	}
	
	ren emp_lbd empl
	*The following does not execute when $routine==_tradables
	cap ren lvapw w1_lvapw
	cap ren ltfp w1_log_TFPr_tfas
	cap gen w1_lspw=log(tvs/empl)
	*The following only executes when $routine==_tradables
	cap gen w1_lspw=log(sales/empl)

	ren lbdnum idnr

	if("`sample'"!="all_w0${routine}" & "`sample"!="all_w25${routine}"){
		cap winsor2 w1_log_TFPr_tfas, replace cuts(1 99)
		cap winsor2 w1_lvapw, replace cuts(1 99)
		winsor2 w1_lspw, replace cuts(1 99)
		}
	if("`sample'"=="all_w25${routine}"){
		cap winsor2 w1_log_TFPr_tfas, replace cuts(2.5 97.5)
		cap winsor2 w1_lvapw, replace cuts(2.5 97.5)
		winsor2 w1_lspw, replace cuts(2.5 97.5)
		}
	
	if("`sample'"=="all_uw${routine}" ){
		replace empl=1
	}
		
	
	if "$routine"=="_tradables"{
	quietly keep if w1_lspw!=.
	}
	else{
	quietly keep if w1_log_TFPr_tfas!=. & w1_lvapw!=. & empl!=. 
	}
	quietly keep if S!=.
	quietly keep if J!=.
	
	
	if("`sample'"=="youngold${routine}" | "`sample'"=="youngold_uw${routine}"){
		quietly bys S J T : egen Nold=	total(age>5 & age<.)
		quietly bys S J T : egen Nyoung	=total(age<=5)		
		keep if Nold>=2 & Nyoung>=2
	}
	else{
		quietly bys S J T: keep if _N>=2
	}
	if("`sample'"=="highcutoff${routine}"){
		quietly bys S J T: keep if _N>=10
	}
	sort linenumber
	quietly gen order=_n

	*For value added column of Table 1, the outcome variable will be value added per worker
	*Here we rename value added as the outcome variable (tfpvar) only for the file used for that column.
	if "${routine}"=="_va" | "`sample'"=="all_va"{
	  ren w1_lvapw tfpvar
	  }
	else if "${routine}"=="_spw" | "${routine}"=="_tradables" {
	  ren w1_lspw tfpvar
	  }
	else{
	  ren w1_log_TFPr_tfas tfpvar
	  }

	save "${data}/data_`sample'", replace
	
}
